package com.ai.service.security.impl;

import com.ai.common.CommonResponse;
import com.ai.entity.security.SysPermission;
import com.ai.entity.security.SysRole;
import com.ai.entity.security.SysRolePermissionRelation;
import com.ai.mapper.security.SysRolePermissionRelationMapper;
import com.ai.model.param.SysRolePermissionParam;
import com.ai.model.param.SysRoleRegionParam;
import com.ai.service.security.ISysPermissionService;
import com.ai.service.security.ISysRolePermissionRelationService;
import com.ai.service.security.ISysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色-权限关联关系表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2023-04-04 19:46:07
 */
@Service
public class SysRolePermissionRelationServiceImpl extends ServiceImpl<SysRolePermissionRelationMapper, SysRolePermissionRelation> implements ISysRolePermissionRelationService {


    @Resource
    private ISysPermissionService sysPermissionService;


    @Resource
    private ISysRoleService iSysRoleService;
    /**
     * 更新指定用户的权限
     * @param permissionParam
     * @return
     */
    @Override
    public CommonResponse<String> updateRolePermission(SysRolePermissionParam permissionParam) {


        String roleId = permissionParam.getRoleId();
        //获取当前橘色所拥有的权限
        List<SysRolePermissionRelation> rolePermissionRelationList =
                this.list(new QueryWrapper<SysRolePermissionRelation>().eq("role_id", roleId));

        List<Integer> permissionIdList =permissionParam.getPermissionIdList();


        //首先是权限id集合为空的情况，  即  摘除当前角色的所有的权限
        if (CollectionUtils.isEmpty(permissionIdList)){
            //角色权限列表为空
            //默认只有查看用户的权限，
            SysRolePermissionRelation sysRolePermissionRelation = rolePermissionRelationList.get(0);
            sysRolePermissionRelation.setPermissionId(2);
            this.updateById(sysRolePermissionRelation);

            //其余权限全部删除
            rolePermissionRelationList.remove(0);
            this.removeBatchByIds(rolePermissionRelationList);

            return CommonResponse.ok("数据更新完成");
        }
        /**
         * 权限列表不为空   确定当前所追加权限是否合法
         *
         */
        ArrayList<Integer> permissionFromParam = new ArrayList<>(permissionIdList);//用于运算的权限id集合
        //获取所有权限id
        List<SysPermission> permissionList = sysPermissionService.list();
        List<Integer> permissionDBIds = permissionList.stream().map(SysPermission::getId).collect(Collectors.toList());

        //前端传入的权限id对db中的权限id做差集，  如果还有剩余则说明具有非法权限
        permissionIdList.removeAll(permissionDBIds);
        if (!CollectionUtils.isEmpty(permissionIdList)){
            //不为空，说明具有非法权限
            return  CommonResponse.error("禁止添加非法权限！！！");
        }
        //更新角色权限
        //先删除用角色所关联的所有权限，然后再新增
        this.removeBatchByIds(rolePermissionRelationList);
        LinkedList<SysRolePermissionRelation> sysRolePermissionRelations = new LinkedList<>();
        for (Integer integer : permissionFromParam) {
            SysRolePermissionRelation sysRolePermissionRelation = new SysRolePermissionRelation();
            sysRolePermissionRelation.setRoleId(Integer.valueOf(roleId));
            sysRolePermissionRelation.setPermissionId(integer);
            sysRolePermissionRelations.add(sysRolePermissionRelation);
        }
        //新增
        this.saveBatch(sysRolePermissionRelations);

        return CommonResponse.ok("角色权限维护完成");
    }

    @Override
    public List<Integer> getBindPermissionList(List<SysRole> bindRoles,boolean isAdmin) {
        List<Integer> permissionIdList = new ArrayList<>();
        if (isAdmin){
            List<SysPermission> permissionList = sysPermissionService.list();
            permissionIdList = permissionList.stream().map(SysPermission::getId).collect(Collectors.toList());
        }else {
            List<Integer> roleIds = bindRoles.stream().map(SysRole::getId).collect(Collectors.toList());
            QueryWrapper<SysRolePermissionRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("permission_id");
            queryWrapper.in("role_id",roleIds);

            List<SysRolePermissionRelation> dbResList = this.list(queryWrapper);
            permissionIdList = dbResList.stream().map(SysRolePermissionRelation::getPermissionId).collect(Collectors.toList());
        }
        return permissionIdList;


    }

    @Override
    public CommonResponse<String> bindUserToRegion(SysRoleRegionParam regionParam) {
        List<Integer> roleIdsParam = regionParam.getRoleIds();
//      先查询出来拥有当前区域的所有角色
        String regionId = regionParam.getRegionId();

        List<SysRolePermissionRelation> regionBindRoles = this.list(
                new QueryWrapper<SysRolePermissionRelation>().eq("permission_id", regionParam.getRegionId()));
        List<Integer> bindRoleIdsDb = regionBindRoles.stream().map(SysRolePermissionRelation::getRoleId).collect(Collectors.toList());
        //用于取界面变更数据和已有数据做交集
        LinkedList<Integer> paramIntersection = new LinkedList<>(roleIdsParam);
        paramIntersection.retainAll(bindRoleIdsDb);
        //取界面和交集的差集 ------ 用于新增用户角色 区域关系
        List<Integer> additionRoleParam =  new LinkedList<>(roleIdsParam);
        additionRoleParam.removeAll(paramIntersection);
        //取DB和交集的差集 ------ 用于删除原本的用户角色 区域关系
        LinkedList<Integer> removeRoleDb = new LinkedList<>(bindRoleIdsDb);
        removeRoleDb.removeAll(paramIntersection);

        //先删后增
        if (!CollectionUtils.isEmpty(removeRoleDb)){
            //需要清除的关系
            this.remove(new QueryWrapper<SysRolePermissionRelation>().eq("permission_id",regionId).in("role_id",removeRoleDb));
        }
        if (!CollectionUtils.isEmpty(additionRoleParam) && additionRoleParam.size()>0){
            List<SysRolePermissionRelation> dbAdditionParam = additionRoleParam.stream().map(roleId -> {
                SysRolePermissionRelation sysRolePermissionRelation = new SysRolePermissionRelation();
                sysRolePermissionRelation.setPermissionId(Integer.valueOf(regionId));
                sysRolePermissionRelation.setRoleId(roleId);
                return sysRolePermissionRelation;
            }).collect(Collectors.toList());
            //批量插入新关系
            this.saveBatch(dbAdditionParam);
        }

        return CommonResponse.ok("修改成功");
    }

    @Override
    public List<Integer> getRolesByPerId(String id) {
        List<Integer> bindIdList = new ArrayList<>();
        QueryWrapper<SysRolePermissionRelation> queryWrapper = new QueryWrapper<SysRolePermissionRelation>().eq("permission_id", id);
        List<SysRolePermissionRelation> permissionRelations = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(permissionRelations)){
            bindIdList = permissionRelations.stream().map(SysRolePermissionRelation::getRoleId).collect(Collectors.toList());
        }
        return bindIdList;
    }

    @Override
    public boolean manageRegionUserRelation(String permissionId, List<Integer> bindUserRoleIds) {
        //首先判断当前是否包含人员信息
        if (CollectionUtils.isEmpty(bindUserRoleIds)){
            //清空当前区域下所有人员关系
            QueryWrapper<SysRolePermissionRelation> queryWrapper = new QueryWrapper<SysRolePermissionRelation>().eq("permission_id", permissionId);
            this.remove(queryWrapper);
            return true;
        }
        //查看原有绑定关系
        List<Integer> rolesByPerId = this.getRolesByPerId(permissionId);

        //用于删除旧关系
        ArrayList<Integer> removeBindRoleIds = new ArrayList<>(rolesByPerId);
        //用于新增新关系
        ArrayList<Integer> newBindRolesIds = new ArrayList<>(bindUserRoleIds);
        newBindRolesIds.removeAll(rolesByPerId);
        removeBindRoleIds.removeAll(bindUserRoleIds);

        if (!CollectionUtils.isEmpty(removeBindRoleIds)){
            //执行删除操作
            QueryWrapper<SysRolePermissionRelation> delWrapper = new QueryWrapper<SysRolePermissionRelation>()
                    .eq("permission_id", permissionId).in("role_id", removeBindRoleIds);
            this.remove(delWrapper);
        }
        if (!CollectionUtils.isEmpty(newBindRolesIds)){
            //执行新增操作
            List<SysRolePermissionRelation> newRelationList = newBindRolesIds.stream().map(roleId -> {
                SysRolePermissionRelation relation = new SysRolePermissionRelation();
                relation.setPermissionId(Integer.valueOf(permissionId));
                relation.setRoleId(roleId);
                return relation;
            }).collect(Collectors.toList());
            this.saveBatch(newRelationList);
        }
        return true;
    }
}
